package com.drg.center.utils;

import cn.hutool.core.util.ArrayUtil;
import com.guaike.core.utils.BigDecimalUtil;
import com.guaike.core.utils.CompareUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.filter.ParsedFilter;
import org.elasticsearch.search.aggregations.metrics.*;

import java.math.BigDecimal;

/**
 * @Author: zhangxilin
 * @Date: 2025/1/7
 */
public class EsResultResolveUtil {

    public static BigDecimal getSumValue(Aggregations aggregations, String fieldName) {
        ParsedSum parsedSum = aggregations.get(fieldName);
        return BigDecimalUtil.parseBigDecimal(parsedSum.getValueAsString());
    }

    public static Integer getSumIntValue(Aggregations aggregations, String fieldName) {
        ParsedSum parsedSum = aggregations.get(fieldName);
        return (int) parsedSum.getValue();
    }

    public static Integer getCardinalityValue(Aggregations aggregations, String fieldName) {
        Cardinality cardinality = aggregations.get(fieldName);
        return (int) cardinality.getValue();
    }

    public static Integer getFilterCount(Aggregations aggregations, String aggName, String fieldName) {
        ParsedFilter parsedFilter = aggregations.get(aggName);
        ValueCount valueCount = parsedFilter.getAggregations().get(fieldName);
        return (int) valueCount.getValue();
    }

    public static Integer getValueCount(Aggregations aggregations, String fieldName) {
        ValueCount valueCount = aggregations.get(fieldName);
        return (int) valueCount.getValue();
    }

    public static String getName(TopHits departNameHits, int index, String fieldName) {
        if (ArrayUtil.isEmpty(departNameHits.getHits().getHits())) {
            return null;
        }
        return (String) departNameHits.getHits().getHits()[index].getSourceAsMap().get(fieldName);
    }

    public static BigDecimal getAvg(Aggregations aggregations, String fieldName) {
        Avg avg = aggregations.get(fieldName);
        String valueAsString = avg.getValueAsString();
        if (StringUtils.isBlank(valueAsString) || CompareUtil.isEqual(valueAsString, "Infinity")) {
            return new BigDecimal(0);
        }
        return BigDecimalUtil.parseBigDecimal(valueAsString);
    }
}
